package com.kai.filter;

import com.kai.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

//拦截所有请求 包括spring里的请求
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        log.info("开始进行token校验");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("请求的url: {}", request.getRequestURI());
        //获取访问地址 判断是不是/login
        if(request.getRequestURI().equals("/login")) {
            //是 放行
            log.info("登录请求 放行");
            filterChain.doFilter(request, response);
            return;
        }

        //获取token 判断token是否存在
        String token = request.getHeader("token");
        log.info("token");
        if(token == null || token.isEmpty()){
            log.info("token不存在");
            log.info(token);
            response.setStatus(HttpStatus.SC_UNAUTHORIZED); //设置状态码 401 表示未授权
            return;
        }

        //判断token是否正确
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //token正确
        log.info("令牌正确, 放行");
        log.info("token校验成功");
        filterChain.doFilter(request, response);


    }
}
